package com.powerunion.datacollection.common;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;

/**
 * 异常类处理类
 * 覆盖execute方法，处理自己的异常类，
 * 其他的异常由父类自己处理
 * @author qyw
 *
 */
public class SystemExceptionHandler extends ExceptionHandler {

	public ActionForward execute(Exception ex, ExceptionConfig ae,
			ActionMapping mapping, ActionForm formInstance,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		
        ActionForward forward = null;
        ActionMessage error = null;
        String property = null;		
		
        if (ae.getPath() != null) {//配置文件中的path
            forward = new ActionForward(ae.getPath());
        } else {
        	//如果没有找到path,转到input配置的路径
            forward = mapping.getInputForward();
        }		
		
        this.logException(ex);
        ex.printStackTrace();
		//处理自定义的异常类SystemException
		if(ex instanceof SystemException){
			SystemException se = (SystemException)ex;
			//如果只有message,而没有key
			if(se.getKey() == null){
				error = new ActionMessage(ae.getKey(), ex.getMessage());
				property = ae.getKey();
			}else{//SystemExcetion中有key值
				error = new ActionMessage(se.getKey(),se.getValues());
				property = se.getKey();
			}
	        request.setAttribute(Globals.EXCEPTION_KEY, ex);
	        this.storeException(request, property, error, forward, ae.getScope());
	        
	        return forward;
		}
		
		return super.execute(ex, ae, mapping, formInstance, request, response);
	}
	
}
